package org.exez.modules.visitor.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.exez.common.api.vo.Result;
import org.exez.common.aspect.annotation.AutoLog;
import org.exez.common.exception.JeecgBootException;
import org.exez.common.system.vo.LoginUser;
import org.exez.common.util.DateUtils;
import org.exez.modules.system.entity.SysUser;
import org.exez.modules.system.service.ISysUserService;
import org.exez.modules.system.util.VisitorBeanUtils;
import org.exez.modules.visitor.constant.AuthorityEnum;
import org.exez.modules.visitor.entity.Institution;
import org.exez.modules.visitor.entity.ReservationApplication;
import org.exez.modules.visitor.entity.VisitorAccessre;
import org.exez.modules.visitor.service.IInstitutionService;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.exez.common.system.base.controller.JeecgController;
import org.exez.modules.visitor.service.IPolicePayService;
import org.exez.modules.visitor.util.AES;
import org.exez.modules.visitor.vo.*;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 事业单位表
 * @Author: exez-boot
 * @Date: 2020-06-04
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "访客事业单位功能接口")
@RestController
@RequestMapping("/visitor/institution")
public class InstitutionController extends JeecgController<Institution, IInstitutionService> {
    @Autowired
    private IInstitutionService institutionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    IPolicePayService iPolicePayService;
    /**
     * 事业单位列表查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "事业单位列表查询")
    @ApiOperation(value = "事业单位列表查询", notes = "事业单位列表查询")
    @GetMapping(value = "/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "institutionName", value = "单位名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页码大小", required = true, dataType = "Integer", paramType = "query"),
    })
    public Result<Page<InstitutionVO>> queryPageList(
            @RequestParam(name = "institutionName",required = false) String institutionName,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Result<Page<InstitutionVO>> result = new Result<>();

        LambdaQueryWrapper<Institution> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Institution::getDeleted, 1);
        if (StringUtils.isNotBlank(institutionName)){
            queryWrapper.like(Institution::getInstitutionName, institutionName);
        }

        if (!AuthorityEnum.ONE_USER.getIndex().equals(sysUser.getAuthority())){
            queryWrapper.eq(Institution::getId, sysUser.getInstitutionId());
        }

        queryWrapper.orderByDesc(Institution::getId);
        Page<Institution> page = new Page<Institution>(pageNo, pageSize);
        IPage<Institution> pageList = institutionService.page(page, queryWrapper);


        Page<InstitutionVO> voPage = new Page<>(pageNo, pageSize);
        BeanUtils.copyProperties(pageList, voPage);
        voPage.setRecords(VisitorBeanUtils.convertList2List(pageList.getRecords(), InstitutionVO.class));

        result.successSetDate(voPage);
        return result;
    }

    /**
     * 事业单位列表查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "公安pay事业单位列表查询")
    @ApiOperation(value = "公安pay事业单位列表查询", notes = "公安pay事业单位列表查询")
    @GetMapping(value = "/policeList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "institutionName", value = "单位名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页码大小", required = true, dataType = "Integer", paramType = "query"),
    })
    public Result<Page<InstitutionPolicePayVO>> policeList(
            @RequestParam(name = "institutionName",required = false) String institutionName,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Result<Page<InstitutionPolicePayVO>> result = new Result<>();

        LambdaQueryWrapper<Institution> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Institution::getDeleted, 1);
        if (StringUtils.isNotBlank(institutionName)){
            queryWrapper.like(Institution::getInstitutionName, institutionName);
        }



        queryWrapper.orderByDesc(Institution::getId);
        Page<Institution> page = new Page<Institution>(pageNo, pageSize);
        IPage<Institution> pageList = institutionService.page(page, queryWrapper);


        Page<InstitutionPolicePayVO> voPage = new Page<>(pageNo, pageSize);
        BeanUtils.copyProperties(pageList, voPage);
        voPage.setRecords(VisitorBeanUtils.convertList2List(pageList.getRecords(), InstitutionPolicePayVO.class));
        List<InstitutionPolicePayVO> records = voPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            InstitutionPolicePayVO institutionPolicePayVO = records.get(i);
            institutionPolicePayVO.setPolicePay(iPolicePayService.selectByInstitutionId(institutionPolicePayVO.getId() + ""));
        }
        voPage.setRecords(records);
        result.successSetDate(voPage);
        return result;
    }

    /**
     * 添加事业单位
     *
     * @param institutionSaveVO
     * @return
     */
    @AutoLog(value = "添加事业单位")
    @ApiOperation(value = "添加事业单位", notes = "添加事业单位")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody InstitutionSaveVO institutionSaveVO) {
		LambdaQueryWrapper<Institution> name = new LambdaQueryWrapper<>();
        name.eq(Institution::getInstitutionName,institutionSaveVO.getInstitutionName());
        name.eq(Institution::getDeleted,1);
		int countName = institutionService.count(name);
		if (countName > 1){
			return Result.error("已存在该事业单位名称："+institutionSaveVO.getInstitutionName());
		}

        LambdaQueryWrapper<Institution> code = new LambdaQueryWrapper<>();
        code.eq(Institution::getCode,institutionSaveVO.getCode());
        code.eq(Institution::getDeleted,1);
        int countCode = institutionService.count(name);
        if (countCode > 1){
            return Result.error("已存在该事业单位编码："+institutionSaveVO.getCode());
        }

		Institution institution = new Institution();
        BeanUtils.copyProperties(institutionSaveVO,institution);
		institution.setCreateTime(DateUtils.getDate());
		institution.setUpdateTime(DateUtils.getDate());
		institution.setDeleted(1);

		institutionService.save(institution);
        return Result.ok("添加成功！");
    }

    /**
     * 修改事业单位信息
     *
     * @return
     */
    @AutoLog(value = "修改事业单位信息")
    @ApiOperation(value = "修改事业单位信息", notes = "修改事业单位信息")
    @PutMapping(value = "/updateById")
    public Result<?> updateById(@RequestBody InstitutionUpdateVO updateVO) {

		LambdaQueryWrapper<Institution> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Institution::getInstitutionName,updateVO.getInstitutionName());
		queryWrapper.ne(Institution::getId,updateVO.getId());

        int count = institutionService.count(queryWrapper);
		if (count > 1){
			return Result.error("已存在该事业单位："+updateVO.getInstitutionName());
		}
        LambdaQueryWrapper<Institution> queryWrapperCode = new LambdaQueryWrapper<>();
        queryWrapperCode.eq(Institution::getCode,updateVO.getCode());
        queryWrapperCode.ne(Institution::getId,updateVO.getId());

        int countCode = institutionService.count(queryWrapperCode);
        if (countCode > 1){
            return Result.error("已存在该事业单位编码："+updateVO.getCode());
        }
        Institution institution = new Institution();
        BeanUtils.copyProperties(updateVO,institution);
		institution.setUpdateTime(DateUtils.getDate());

        institutionService.updateById(institution);
        return Result.ok("编辑成功!");
    }
    /**
     * 修改事业单位信息
     *
     * @return
     */
    @AutoLog(value = "修改事业单位预留时间")
    @ApiOperation(value = "修改事业单位预留时间", notes = "修改事业单位预留时间")
    @PutMapping(value = "/updateReserveTime")
    public Result<?> updateReserveTime(@Validated @RequestBody InstitutionTimeUpdateVO updateVO) {

        Institution institution = new Institution();
        BeanUtils.copyProperties(updateVO,institution);
        institution.setUpdateTime(DateUtils.getDate());

        institution.setId(updateVO.getInstitutionId());

        institutionService.updateById(institution);
        return Result.ok("编辑成功!");
    }

    /**
     * 修改事业单位信息
     *
     * @return
     */
    @AutoLog(value = "获取事业单位信息")
    @ApiOperation(value = "获取事业单位信息", notes = "获取事业单位信息")
    @GetMapping(value = "/getInstitution")
    public Result<Institution> getInstitution() {
        Result<Institution> result = new Result<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Institution byId = institutionService.getById(sysUser.getInstitutionId());
        result.successSetDate(byId);
        return result;
    }



    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "事业单位通过id删除")
    @ApiOperation(value = "事业单位通过id删除", notes = "事业单位通过id删除")
    @GetMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Integer id) {
        Institution institution = new Institution();
        institution.setId(id);
        institution.setDeleted(0);
        Integer integer = userService.countByInstitution(id);
        if (integer > 0 ){
            throw new JeecgBootException("该单位下面还有员工,不能删除");
        }
        institutionService.updateById(institution);
        return Result.ok("删除成功!");
    }

//    /**
//     * 批量删除
//     *
//     * @param ids
//     * @return
//     */
//    @AutoLog(value = "事业单位表-批量删除")
//    @ApiOperation(value = "事业单位表-批量删除", notes = "事业单位表-批量删除")
//    @DeleteMapping(value = "/deleteBatch")
//    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
//        this.institutionService.removeByIds(Arrays.asList(ids.split(",")));
//        return Result.ok("批量删除成功！");
//    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id查询")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        Institution institution = institutionService.getById(id);
        return Result.ok(institution);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param institution
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Institution institution) {
        return super.exportXls(request, institution, Institution.class, "事业单位表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Institution.class);
    }

    /**
     * 用户单位权限
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "单位列表")
    @ApiOperation(value = "用户权限--单位列表", notes = "单位列表")
    @GetMapping(value = "/queryPageQxList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "institutionName", value = "单位名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页码大小", required = false, dataType = "Integer", paramType = "query"),
    })
    public Result<IPage<Institution>> queryPageQxList(
            @RequestParam(name = "institutionName",required = false) String institutionName,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10000") Integer pageSize) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Result<IPage<Institution>> result = new Result<>();

        LambdaQueryWrapper<Institution> queryWrapper = new LambdaQueryWrapper<>();
         if (!AuthorityEnum.ONE_USER.getIndex().equals(sysUser.getAuthority())) {
             queryWrapper.in(Institution::getId, AES.integerList(sysUser.getInstitutionId()));
        }

        queryWrapper.eq(Institution::getDeleted, 1);
        if (StringUtils.isNotBlank(institutionName)){
            queryWrapper.like(Institution::getInstitutionName, institutionName);
        }
        queryWrapper.orderByDesc(Institution::getId);
        Page<Institution> page = new Page<Institution>(pageNo, pageSize);
        IPage<Institution> pageList = institutionService.listInstitution(page, queryWrapper);

        result.setResult(pageList);
        return result;
    }


    /**
     * 用户单位权限
     *
     * @param
     * @return
     */
    @AutoLog(value = "用户单位权限--保存用户权限")
    @ApiOperation(value = "用户单位权限--保存用户权限", notes = "用户单位权限--保存用户权限")
    @GetMapping(value = "/saveUserQx")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "userId", value = "分配权限用户的id", required = false, dataType = "String", paramType = "query"),
                @ApiImplicitParam(name = "institutionList", value = "页码", required = false, dataType = "String", paramType = "query"),
        })
        public Result<?> saveUserQx(
                @RequestParam(name = "userId",required = false) String userId,
                @RequestParam(name = "institutionList",required = false) String institutionList) {
        institutionService.saveUserQx(userId,institutionList);
        return Result.ok("保存成功!");
    }

    /**
     * 事业单位列表查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "用户id获取单位集合")
    @ApiOperation(value = "用户id获取单位集合", notes = "用户id获取单位集合")
    @GetMapping(value = "/userInstitutionlist")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "账号id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页码大小", required = false, dataType = "Integer", paramType = "query"),
    })
    public Result<IPage<Institution>> userInstitutionlist(
            @RequestParam(name = "userId",required = false) String userId,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10000") Integer pageSize) {
        SysUser byId = userService.getById(userId);
        Result<IPage<Institution>> result = new Result<>();
        Page<Institution> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<Institution> queryWrapper = new LambdaQueryWrapper<>();
        List<Integer> list = AES.integerList(byId.getInstitutionId());
        queryWrapper.in(Institution::getId, list);
        IPage<Institution> lists = institutionService.listInstitution(page, queryWrapper);
        result.setResult(lists);
        return result;
    }
}
